'use strict';
const crypto = require("crypto");

module.exports = app => {
    const { STRING, INTEGER, DATE, ENUM } = app.Sequelize;
    // 配置（重要：一定要配置详细，一定要！！！）
    const AdminUser = app.model.define('admin_user', {
        id: {
            type: INTEGER(30).UNSIGNED,
            primaryKey: true,
            autoIncrement: true
        },
        depart_id: {
            type: INTEGER(30).UNSIGNED,
            comment: '部门id',
            //  定义外键（重要）
            references: {
                model: 'admin_depart', // 对应表名称（数据表名称）
                key: 'id' // 对应表的主键
            },
            onUpdate: 'restrict', // 更新时操作
            onDelete: 'setnull'  // 删除时操作
        },
        phone: {
            type: STRING(100),
            allowNull: false,
            defaultValue: 0,
            comment: '手机号',
        },
        pwd: {
            type: STRING(200),
            allowNull: false,
            defaultValue: '',
            comment: '密码',
            set(val) {
                const hmac = crypto.createHash("sha256", app.config.crypto.secret);
                hmac.update(val);
                let hash = hmac.digest("hex");
                this.setDataValue('pwd', hash);
            }
        },
        avatar: {
            type: STRING(200),
            comment: '头像',
        },
        name: {
            type: STRING(100),
            allowNull: false,
            defaultValue: '',
            comment: '昵称',
        },
        roles: {
            type: STRING(200),
            allowNull: false,
            defaultValue: 'admin',
            comment: '权限',
        },
        nav_id: {
            type: STRING(200),
            allowNull: false,
            defaultValue: '',
            comment: '导航栏id',
        },
        btn_id: {
            type: STRING(200),
            allowNull: false,
            defaultValue: '',
            comment: '导航栏id',
        },
        token: {
            type: STRING(200),
            allowNull: false,
            defaultValue: '',
            comment: 'token',
        },
        status: {
            type: ENUM,
            values: ['0', '1', '2'],
            allowNull: false,
            defaultValue: '1',
            comment: '状态 0离职 1在职 2删除 '
        },
        created_at: DATE,
        updated_at: DATE,
    });

    // 定义关联关系
    AdminUser.associate = function (model) {
        AdminUser.belongsTo(app.model.AdminDepart, {
            foreignKey: 'depart_id'
        });    
    };
    return AdminUser;
};